package com.klxedu.ms.gateway.security.authentication.impl;

import com.klxedu.ms.gateway.AuthServerConstants;
import com.klxedu.ms.gateway.core.json.BaseJsonObject;
import com.klxedu.ms.gateway.security.authentication.IAuthenticateAction;
import com.klxedu.ms.gateway.security.authentication.IAuthenticatedUser;
import com.klxedu.ms.gateway.security.client.UserFeignClient;
import com.klxedu.ms.gateway.security.client.service.LoginUser;
import com.klxedu.ms.gateway.utils.SpringBeanUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public abstract class AbstraAuthenticateAction implements IAuthenticateAction {

    abstract BaseJsonObject<LoginUser> getLoginUser(String login);

    @Override
    public IAuthenticatedUser doAuthenticate(String userName) throws AuthenticationException {
        BaseJsonObject<LoginUser> jsonResult = getLoginUser(userName);
        LoginUser loginUser = jsonResult.getData();
        if (loginUser == null || loginUser.getAccountID() == null || "".equals(loginUser.getAccountID())
                || loginUser.getState() == LoginUser.STATE_OFF) {
            throw new UsernameNotFoundException("账号不存在: " + userName);
        }
//		if (loginUser.getState() == LoginUser.STATE_NOTACTIVE) {
//			throw new UsernameNotFoundException("账号未激活: " + userName);
//		}
        if (loginUser.getState() == LoginUser.STATE_LOCKED) {
            throw new UsernameNotFoundException("账号已锁定: " + userName);
        }
        AuthenticatedUserImpl user = new AuthenticatedUserImpl(loginUser.getUserID(), loginUser.getUserName(),
                loginUser.getPasswd(), userName, loginUser.getOrgID());
        user.setName(loginUser.getName());
        List<Map<String, String>> scopeMapList = loginUser.getScopeMapList();
        if(scopeMapList!=null && !scopeMapList.isEmpty()) {
            List<String> scopeCodes = new ArrayList<>();
            List<String> unitScopeCodes = new ArrayList<>();
            for(Map<String,String> scopeMap : scopeMapList) {
                String scopeCode = scopeMap.get(AuthServerConstants.SCOPE_CODE_KEY);
                scopeCodes.add(scopeCode);
                String unitScopeCode = scopeMap.get(AuthServerConstants.UNIT_SCOPE_CODE_KEY);
                unitScopeCodes.add(unitScopeCode);
            }
            user.setUnitScopeCodes(unitScopeCodes.toArray(new String[0]));
            user.setScopeCodes(scopeCodes.toArray(new String[0]));
        }
        user.setAccountID(loginUser.getAccountID());
        user.setState(loginUser.getState());
        user.setSysIdentityCodes(loginUser.getSysIdentityCodes().toArray(new String[0]));
        return user;
    }

}